package com.kum.utils;

import com.alibaba.fastjson.JSON;
import com.kum.domain.R;
import com.kum.domain.entity.SysUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version V1.0
 * @Package com.kum.utils
 * @auhter 枯木Kum
 * @date 2021/3/19-4:32 PM
 */
public class RequestUtils {

    /**
     * 获取当前线程的Request对象
     *
     * @return
     */
    public static HttpServletRequest getCurrentRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取当前线程的Response对象
     *
     * @return
     */
    public static HttpServletResponse getCurrentResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static void setCurrentSessionAttribute(String key, Object val) {
        getCurrentRequest().getSession().setAttribute(key, val);
    }

    public static void removeCurrentSessionAttribute(String key) {
        getCurrentRequest().getSession().removeAttribute(key);
    }

    public static Object getCurrentSessionAttribute(String key) {
        return getCurrentRequest().getSession().getAttribute(key);
    }

    /**
     * 删除当前Session
     */
    public static void invalidate() {
        getCurrentRequest().getSession().invalidate();
    }


    public static String getCurrentLoginUserId() {
        SysUser loginUser = getCurrentLoginUser();
        if (loginUser == null) {
            return "";
        }
        return loginUser.getId();
    }
    public static SysUser getCurrentLoginUser() {
        String token = getCurrentRequest().getHeader("token");
        SysUser user = null;
        if (token == null || (user = JwtUtil.getPayload(token)) == null) {
            return null;
        }
        return user;
    }


    public static void forbidden() {
        ServletUtils.renderString(getCurrentResponse(), JSON.toJSONString(R.fail()));
    }

    public static void tokenInvalid(){
        ServletUtils.renderString(getCurrentResponse(), JSON.toJSONString(R.invalid()));

    }

}
